package com.onlineClass.edu.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.onlineClass.edu.cache.LocalCache;
import com.onlineClass.edu.constant.LocalCacheKeyConstants;
import com.onlineClass.edu.entity.EduCourse;
import com.onlineClass.edu.entity.dto.response.EduCourseClassRespDto;
import com.onlineClass.edu.entity.dto.response.EduCourseRespDto;
import com.onlineClass.edu.entity.requestDto.EduCourseReqDto;
import com.onlineClass.edu.mapper.EduCourseMapper;
import com.onlineClass.edu.service.IEduCourseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 课程表 服务实现类
 * </p>
 *
 * @author denghui
 * @since 2024-05-01
 */
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements IEduCourseService {
@Autowired
private EduCourseMapper eduCourseMapper;

    @Override
    public List<EduCourse> getAll() {
        return eduCourseMapper.selectList(new QueryWrapper<>());
    }

    /**
     * 从缓存里获取课程数据
     * @param reqDto
     * @return
     */
    @Override
    public List<EduCourseRespDto> searchFromCache(EduCourseReqDto reqDto) {
        List<EduCourseRespDto> eduCourseDTOs = new ArrayList<>();
        eduCourseDTOs = LocalCache.get(LocalCacheKeyConstants.COURSE_ALLCOURSELIST,eduCourseDTOs);
        if (CollectionUtils.isEmpty(eduCourseDTOs)){
            log.error("[EduCourseServiceImpl 未查找到数据]");
            return null;
        }
        Integer subjectId = reqDto.getSubjectId();
        Stream<EduCourseRespDto> eduCourseStream = eduCourseDTOs.stream();
        if (!Objects.isNull(subjectId)){
            eduCourseStream = eduCourseStream.filter(c->c.getCourseId().equals(subjectId));
        }
        String courseName = reqDto.getCourseName();
        if (!StringUtils.isEmpty(courseName)){
            eduCourseStream = eduCourseStream.filter(c-> StrUtil.containsAnyIgnoreCase(c.getCourseName(),courseName));
        }

        return eduCourseStream.sorted(Comparator.comparing(EduCourseRespDto::getUpdateTime)).collect(Collectors.toList());
    }
}
